package com.at;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

@javax.servlet.annotation.WebServlet(
        // servlet name
        name = "async",
        // servlet url pattern
        value = {"/async"},
        // async support needed
        asyncSupported = true
)
public class SimpleAsyncServlet extends HttpServlet {

    @Override
    public void service(final ServletRequest req, final ServletResponse res)
            throws ServletException, IOException {
        req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        final String id = req.getParameter("id");
        // create the async context, otherwise getAsyncContext() will be null
        final AsyncContext ctx = req.startAsync();
        // set the timeout
        ctx.setTimeout(1000);
        // attach listener to respond to lifecycle events of this AsyncContext
        ctx.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent event) throws IOException {
                log("onComplete(): "+id);
            }

            @Override
            public void onTimeout(AsyncEvent event) throws IOException {
                log("onTimeout(): "+ id);
            }

            @Override
            public void onError(AsyncEvent event) throws IOException {
                log("onError(): "+ id);
            }

            @Override
            public void onStartAsync(AsyncEvent event) throws IOException {
                log("onStartAsync(): "+ id);
            }
        });
        // spawn some task in a background thread
        ctx.start(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    ctx.getResponse().getWriter().write(
                            MessageFormat.format("<h1>Processing task in bgt_id:[{0}]</h1>",
                                    id));
                } catch (IOException e) {
                    log("Problem processing task", e);
                } catch (InterruptedException ex) {
                    Logger.getLogger(SimpleAsyncServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                ctx.complete();
            }
        });
    }

}
